package com.roper.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.roper.yygh.hosp.repository.ScheduleRepository;
import com.roper.yygh.hosp.service.ScheduleService;
import com.roper.yygh.model.hosp.Schedule;
import com.roper.yygh.vo.hosp.ScheduleQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * Description: 排班接口查询类
 * Date:      2021/11/23 20:30
 * author:    LPH
 * version:   V1.0
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    // 保存排班信息
    @Override
    public void save(Map<String, Object> map) {
        // 先将map转为String  再将String转为对象
        String mapString = JSONObject.toJSONString(map);
        Schedule schedule = JSONObject.parseObject(mapString, Schedule.class);
        Date date = new Date();

        // 先根据医院编号和排班编号判断排班是否存在
        Schedule scheduleByHoscode = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        // 更新
        if(scheduleByHoscode != null) {
            schedule.setUpdateTime(date);
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }else {
            // 插入
            schedule.setCreateTime(date);
            schedule.setUpdateTime(date);
            schedule.setIsDeleted(0);
            scheduleRepository.insert(schedule);
        }
    }

    // 删除排班接口
    @Override
    public void removeSchedule(String hosCode, String hosScheduleId) {
        Schedule scheduleByHoscode = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hosCode, hosScheduleId);
        if(scheduleByHoscode != null) {
            scheduleRepository.delete(scheduleByHoscode);
        }
    }

    // 查询排班接口
    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        Pageable pageable = PageRequest.of(page, limit);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Schedule> example = Example.of(schedule, matcher);
        return scheduleRepository.findAll(example, pageable);
    }
}
